package com.ms.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import java.util.List;
import java.util.Map;

public class JsonUtil {

    public static String mapToJson(Map<String, Object> map) {
        if ((map == null) || (map.size() == 0)) {
            return null;
        }
        return JSON.toJSONString(map);
    }

    public static String toJson(Object obj) {
        if (obj == null) {
            return null;
        }
        return JSON.toJSONString(obj);
    }

    public static <T> T toObject(String text, Class<T> clazz) {
        if (text == null) {
            return null;
        }
        return JSON.parseObject(text, clazz);
    }

    @SuppressWarnings("unchecked")
    public static <T> T toObject(String text) {
        if (text == null) {
            return null;
        }
        return (T) JSON.parseObject(text);
    }

    @SuppressWarnings("unchecked")
    public static Map<String, Object> jsonToMap(String jsonStr) throws Exception {
        if ((jsonStr == null) || (StringUtils.isEmpty(jsonStr))) {
            return null;
        }
        return JSON.parseObject(jsonStr, Map.class);
    }

    public static Map<String, Object> jsonToMap2(String jsonStr) throws Exception {
        if ((jsonStr == null) || (StringUtils.isEmpty(jsonStr))) {
            return null;
        }
        return JSON.parseObject(jsonStr, new TypeReference<Map<String, Object>>() {
        });
    }

    public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
        return (List<T>) JSONArray.parseArray(jsonString, clazz);
    }

}